#include <iostream>
#include <thread>
#include <mutex>
using namespace std;

template <typename Mutex>
class my_lock_guard
{
public:
    explicit my_lock_guard(Mutex &m) : mutex_(m)
    {
        mutex_.lock(); // 构造时加锁
    }

    ~my_lock_guard()
    {
        mutex_.unlock(); // 析构时解锁
    }

    // 删除拷贝构造和赋值，防止误用
    my_lock_guard(const my_lock_guard &) = delete;
    my_lock_guard &operator=(const my_lock_guard &) = delete;

private:
    Mutex &mutex_;
};
std::mutex mtx;
void foo(int &num)
{
    my_lock_guard<mutex> lock{mtx};
    num++;
}
int main()
{
    int num{1};
    thread t1(foo, ref(num));
    thread t2(foo, ref(num));
    t1.join();
    t2.join();
    cout << "num is " << num << endl;
    return 0;
}